package org.example.utils;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import jakarta.servlet.http.HttpServletRequest;
import org.example.domain.vo.LoginUserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.UUID;

@Component
public class JWTUtil {
    @Autowired
    public  RedisCacheUtil redisCacheUtil;

    @Autowired
    public RedisTemplate redisTemplate;

    public String createToken(LoginUserVo loginUserVo){
        HashMap<String, Object> claim = new HashMap<>();
        String token = UUID.randomUUID().toString().replace("-", "");
        System.out.println("uuid---------"+token);
        loginUserVo.setToken(token);
        claim.put("tokenUUID",token);
        redisCacheUtil.setCacheObject(token,loginUserVo);
        //redisTemplate.opsForValue().set(token, loginUserVo);

        return Jwts.builder().setClaims(claim)
                .signWith(SignatureAlgorithm.HS256,"vivid")
                .compact();
    }

    public Claims parseToken(String token){
        return Jwts.parser()
                .setSigningKey("vivid")
                .parseClaimsJws(token)
                .getBody();
    }

    public  LoginUserVo getToken(String token){
        String tokenUUID = (String) parseToken(token).get("tokenUUID");
        LoginUserVo loginUser = redisCacheUtil.getCacheObject(tokenUUID);
        return loginUser;
    }

    public LoginUserVo getLoginUser(HttpServletRequest request){
        String token = request.getHeader("Authorization");
        System.out.println("前端返回的token======》"+token);
        //String header = request.getHeader("Vivid-Authorization");
        String parseToken = (String) parseToken(token).get("tokenUUID");
        LoginUserVo loginUser = redisCacheUtil.getCacheObject(parseToken);

        return loginUser;
    }

    public static void main(String[] args) {
        JWTUtil jwtUtil = new JWTUtil();
        Claims claim = jwtUtil.parseToken("eyJhbGciOiJIUzI1NiJ9.eyJ0b2tlblVVSUQiOiIxNjU4YmE4ZTlkMzk0YmJhYTAyNWNlOGVkNWIyMTBiMiJ9.wWh_jX_8Gk2sgMDli61dIM1hxcPVRxG4HSqC5A0PmmQ");
        String tokenUUID = (String) claim.get("tokenUUID");
        System.out.println(tokenUUID+"-----");
    }
}
